package cn.cl;

import org.jboss.netty.channel.ServerChannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NIOServerTest {
    private static List<SocketChannel> channels = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(9000));
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        System.out.println("服务启动成功");
        while (true) {
            //非阻塞模式的accept方法不会阻塞，否则会阻塞
            //NIO的非阻塞是由操作系统内部实现的，底层调用了linux内核的accpet函数
            SocketChannel accept = socketChannel.accept();
            if (accept != null) {
                //设置为非阻塞
                accept.configureBlocking(false);
                channels.add(accept);
            }

            //遍历进行数据读取
            Iterator<SocketChannel> iterator = channels.iterator();
            while (iterator.hasNext()) {
                SocketChannel channel = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int len = channel.read(byteBuffer);
                if (len > 0) {
                    System.out.println("接收到消息："+new String(byteBuffer.array()));
                } else if (len == -1) {
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }

        }
    }
}
